package com.javafactroy.kunlong.base.metadata.model;


import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.javafactroy.kunlong.base.config.datasource.oracle.OracleDatasourceConfig;
import com.javafactroy.kunlong.base.metadata.valueobj.MetadataField;
import com.javafactroy.kunlong.base.metadata.valueobj.MetadataTable;
import com.javafactroy.kunlong.codefactroy.convert.OracleColumnsConvert;
import com.javafactroy.kunlong.codefactroy.convert.TmetadataFieldConvert;
import com.javafactroy.kunlong.data.dao.oracle.OracleColumnsMapper;
import com.javafactroy.kunlong.data.entity.mysql.MysqlColumns;
import com.javafactroy.kunlong.data.entity.oracle.OracleColumns;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.util.List;

//@Service
@Qualifier("TMetadataModelPostgres")
@ConditionalOnProperty(prefix = "spring.datasource.postgres", name = "enabled", havingValue = "true")
public class TMetadataModelOracle extends TMetadataModel {
    @Autowired
    OracleColumnsMapper oracleColumnsMapper;
    @Autowired
    OracleDatasourceConfig oracleDatasourceConfig;

    @Autowired
    OracleColumnsConvert oracleColumnsConvert;

    public List<MysqlColumns> selectPostgresColumns(String tableName) {
        PageHelper.orderBy("ORDINAL_POSITION asc");

        List<OracleColumns> list = oracleColumnsMapper.select(new OracleColumns()
                .setDbName(oracleDatasourceConfig.getDbName()).setTableName(tableName));

        return oracleColumnsConvert.fromList(list);
    }

    public MetadataTable loadDbPostgresMetadata(String tableName) {
        List<MysqlColumns> list = selectPostgresColumns(tableName);
        List<MetadataField> fieldList = TmetadataFieldConvert.INSTANCE.fromList(list);
        fieldList.forEach(i -> {
            i.setPropName(StrUtil.toCamelCase(i.getColName()));
            i.setPropType(i.dataType2PropTypePostgres());
            i.setJdbcType(i.datatype2JdbcTypePostgres());
        });
        String dbName = oracleDatasourceConfig.getDbName();
        return new MetadataTable().setDbName(dbName).setTableName(tableName).setFieldList(fieldList);

    }
}
